package com.wing.productionPlan.controller.admin;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.wing.common.enums.MaintenanceEnum;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.productionPlan.model.request.DeviceTypeForm;
import com.wing.productionPlan.model.response.ProductionTheWorkOrderSearchVO;
import com.wing.productionPlan.model.response.ProductionTheWorkOrderVO;
import com.wing.productionPlan.service.ProductionProcessService;
import com.wing.productionPlan.service.ProductionTheWorkOrderService;
import com.wing.productionPlan.service.ProductionWorkOrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

import static com.wing.productionPlan.model.entity.ProductionTheWorkOrder.Status.sendOver;

/**
 * 报工单-Controller
 *
 * @author xiayang
 */
@Slf4j
@Validated
@Api(value = "Admin-生产报工单核定管理", tags = "#/productionPlan/productionTheWorkOrderCheck")
@RestController("productionTheWorkOrderCheckController")
@RequestMapping("productionPlan/admin/productionTheWorkOrderCheck")
@RequiredArgsConstructor
public class ProductionTheWorkOrderCheckController {
    private final ProductionTheWorkOrderService productionTheWorkOrderService;
    private final ProductionWorkOrderService productionWorkOrderService;
    private final ProductionProcessService productionProcessService;


    @ApiOperation(value = "查询所有生产报工单", notes = "搜索")
    @GetMapping("/list")
    public PageResult<ProductionTheWorkOrderVO> list(
        @RequestParam(defaultValue = "1") Integer page,
        @RequestParam(defaultValue = "10") Integer limit,
        @RequestParam(defaultValue = "create_time") String sort,
        @RequestParam(defaultValue = "asc") String order,
        ProductionTheWorkOrderVO productionTheWorkOrderVO
    ) {
        productionTheWorkOrderVO.setStatusRange(sendOver.getValue());
        IPage<ProductionTheWorkOrderVO> pageList = productionTheWorkOrderService.getProductionTheWorkOrderVOPageList(productionTheWorkOrderVO, page, limit);

        List<ProductionTheWorkOrderVO> records = pageList.getRecords();
        if (CollectionUtil.isNotEmpty(records)) {
            for (ProductionTheWorkOrderVO record : records) {
                //计算剩余数
                if (record.getStatus().getValue().equals(sendOver.getValue())){
                    record.setRemainderSentQuantity(0);
                }else{
                    // 报工数-送检数
                    int haveSendQuantity = record.getQualityQuantity()==null?0:record.getQualityQuantity();
                    int remainderSentQuantity = record.getWorkQuantity() - haveSendQuantity;
                    record.setRemainderSentQuantity(remainderSentQuantity);
                }

                //质检性质
                String qualityAttributes = this.productionWorkOrderService.getQualityAttributes(record.getWorkOrderId());
                record.setQualityAttributes(qualityAttributes);

                List<String> list = new ArrayList<>();
                list.add(record.getDeviceCode());
                List<DeviceTypeForm> deviceTypeFormList = this.productionProcessService.getDevicetTypeList(list);
                if (CollectionUtil.isNotEmpty(deviceTypeFormList)) {
                    record.setDeviceCode(deviceTypeFormList.get(0).getName());
                }
                String typeLies = this.productionWorkOrderService.getTypeLies(record.getWorkOrderId());
                if (StrUtil.isNotBlank(typeLies)) {
                    record.setType(typeLies);
                }
                //报工合格数
                BigDecimal numeratorBd = new BigDecimal(record.getWorkQuantity() - record.getQualifiedNoQuantity());
                //报工合格数
                record.setQualifiedQuantity(record.getWorkQuantity() - record.getQualifiedNoQuantity());
                //报工数
                if (numeratorBd.compareTo(BigDecimal.ZERO) != 0) {
                    BigDecimal workQuantity = new BigDecimal(record.getWorkQuantity());
                    // 执行除法，保留两位小数，使用四舍五入
                    BigDecimal percentage = numeratorBd.divide(workQuantity, 4, RoundingMode.HALF_UP).multiply(new BigDecimal(100));
                    // 设置保留两位小数
                    BigDecimal result = percentage.setScale(2, RoundingMode.HALF_UP);
                    record.setBgOkRate(result);
                }else{
                    record.setBgOkRate(new BigDecimal("100.00"));
                }
                //样品合格数
                //送检数
                BigDecimal sendQuantity = new BigDecimal(record.getSendQuantity());
                if (sendQuantity.compareTo(BigDecimal.ZERO) != 0){
                    //送检数(分母)
                    if (numeratorBd.compareTo(BigDecimal.ZERO) != 0) {
                        //送检合格数
                        BigDecimal hgs = new BigDecimal(record.getSendQuantity() - record.getQualifiedNoQuantity());
                        // 执行除法，保留两位小数，使用四舍五入
                        BigDecimal percentage = hgs.divide(sendQuantity, 4, RoundingMode.HALF_UP).multiply(new BigDecimal(100));
                        // 设置保留两位小数
                        BigDecimal result = percentage.setScale(2, RoundingMode.HALF_UP);
                        record.setYpOkRate(result);
                    }else{
                        record.setYpOkRate(new BigDecimal("100.00"));
                    }
                }else{
                    record.setYpOkRate(new BigDecimal("100.00"));
                }
            }
        }

        return new PageResult<>(pageList.getRecords(), pageList.getTotal());
    }

    @ApiOperation(value = "查看报工单详情", notes = "报工-详情")
    @GetMapping("detail/{id}")
    public JsonResult<ProductionTheWorkOrderSearchVO> getDetailBy(@PathVariable("id") Long id) {
        ProductionTheWorkOrderSearchVO productionTheWorkOrderVO =  productionTheWorkOrderService.getDetailBy(id);
        if (ObjectUtil.isNotEmpty(productionTheWorkOrderVO)) {
            productionTheWorkOrderVO.setTypeName(MaintenanceEnum.gxTypeEmum.getNameByCode(productionTheWorkOrderVO.getType()));
            productionTheWorkOrderVO.setWorkstationNatureName(MaintenanceEnum.workstationEmum.getNameByCode(productionTheWorkOrderVO.getWorkstationNature()));
        }
        return JsonResult.success(productionTheWorkOrderVO);
    }
}
